'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  BackAndroid,
  TouchableOpacity,
  ListView,
  Navigator,
  Image,
  TouchableHighlight,
  Dimensions,
  TouchableWithoutFeedback,
  DeviceEventEmitter,
} from 'react-native';

import Modal from 'react-native-root-modal';
import RNFileSearch from './RNFileSearch';
import MediaControl from './MediaControl';
import ToolbarAndroid from 'ToolbarAndroid';
import SortView from './SortView';
import DownloadControl from './DownloadControl';
import ProgressBarAndroid from 'ProgressBarAndroid';
import Video from '../Common/Video';
import * as FileTypeFilter from './FileTypeFilter'
import DownloadCenter from './DownloadCenter';
import getStorage from '../Common/storage.js';
import TimeLine from '../Common/TimeLine.js';
import Tag from './Tag.js';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {FileIcon} from '../Common/utils/FileUtil'

var FileTransfer = require('@remobile/react-native-file-transfer');
var width = Dimensions.get('window').width;
var TimerMixin = require('react-timer-mixin');
var tempData = [];

//http://42.159.143.17:6080/alfresco/service/dms/getFolder?path=/User Homes/tw.feng@haihangyun.com
  var urls = ["http://42.159.143.17:6080/alfresco/service/dms/getFolder?path=/User Homes/tw.feng@haihangyun.com"];

class MainScreen extends Component{


  constructor(props){
    super(props);
    Array.prototype.remove = function(val) {
      var index = this.indexOf(val);
      if (index > -1) {
          this.splice(index, 1);
      }
   }


    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
      data: null,//云上获取的数据
      edit: false,
      checkRows: [],
      centerWindow: false,  //判断中间弹窗
      bottmWindow: false,  //判断底部弹窗
      topWindow: false,  //判断顶部弹窗
      mixins: [TimerMixin]
    };
    this.downloadCenter = DownloadCenter();
    this.downloadCenter.getDbDatas();
  }

  componentDidMount() {
    // this.timer =  TimerMixin.(()=>{console.log('把一个定时器的引用挂在this上')},2000);
    // var url = "http://42.159.150.5:7080/alfresco/service/dms/getFolder?path=/User Homes/tw.feng@haihangyun.com";
    this.setState({edit:false})
    this.fetchData(urls[0]);
    tempData[urls.length-1] = this.state.data;
    BackAndroid.addEventListener('hardwareBackPress', () => {
      if(this.state.centerWindow===true){
        this.state.centerWindow = false;
        this.setState({centerWindow:false});
        return true;
      }
      if(this.state.edit===true){
        this.state.edit = false;
        this.setState({edit:false});
        return true;
      }
      if(this.state.topWindow===true){
        this.state.topWindow = false;
        this.setState({topWindow:false});
        return true;
      }
      if (urls.length>1) {
        this.state.data = tempData[urls.length-2]
        this.setState({
          dataSource:this.state.dataSource.cloneWithRows(tempData[urls.length-2])
        })
        urls.pop()
        tempData.pop()
        return true
      }
    });
  }
  componentWillUnmount() {
    BackAndroid.removeEventListener('hardwareBackPress');
  }


  fetchData(url){
    // var arr = [];
    // var arr1 = [5,6,7];
    // console.log('concat',arr.concat(arr1));
    fetch(url,{ method:'get',headers:{'Content-Type':'application/json','Authorization': 'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE='}})
          .then((response) => response.json())
          .then((responseData) => {
            this.state.data = responseData.results.items
            tempData[urls.length-1] = this.state.data
            this.setState({
              dataSource: this.state.dataSource.cloneWithRows(this.state.data)
            });
          })
          .catch((error) => {
            console.log('请求失败');
            console.log(error);
          })
          .done();
  }

  goEdit(){
    if(this.state.edit == false){
        this.setState({edit: true,bottmWindow: true});
    }else{
        this.setState({edit: false,bottmWindow: false});
    }
  }



  goFile(){
    var fileDatas = FileTypeFilter.getFileByType(this.state.data,'doc');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(fileDatas),topWindow: false});
  }

  goSlide(){
    var slideDatas = FileTypeFilter.getFileByType(this.state.data,'ppt');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(slideDatas),topWindow: false});
  }

  goPic(){
    var picDatas = FileTypeFilter.getFileByType(this.state.data,'pic');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(picDatas),topWindow: false});
  }

  goMusic(){
    var musicDatas = FileTypeFilter.getFileByType(this.state.data,'music');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(musicDatas),topWindow: false});
  }

  goVideo(){
    var videoDatas = FileTypeFilter.getFileByType(this.state.data,'video');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(videoDatas),topWindow: false});
  }


  goLabel(){
    var labelDatas = FileTypeFilter.getFileByType(this.state.data,'label');
    this.setState({dataSource:this.state.dataSource.cloneWithRows(labelDatas),topWindow: false});
  }

  goRecent(){
    this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.data),topWindow: false});
  }

  fileSort(){
    this.setState({centerWindow:false})
    const { navigator } = this.props;
    if(navigator) {
      navigator.push({
        name: 'sortview',
        component : SortView,
        params: {
          type: "file",
          cloud: this.state.data,
          downloadCenter:this.downloadCenter
        }
      });
    }
  }
  slideSort(){
    this.setState({centerWindow:false})
     const { navigator } = this.props;
        if(navigator) {
          navigator.push({
              name: 'sortview',
              component : SortView,
              params: {
                  type: "slide",
                  cloud: this.state.data,
                  downloadCenter:this.downloadCenter
              }
          });
        }
  }
  picSort(){
    this.setState({centerWindow:false})

     const { navigator } = this.props;
        if(navigator) {
          navigator.push({
              name: 'sortview',
              component : SortView,
              params: {
                  type: "pic",
                  cloud: this.state.data,
                  downloadCenter:this.downloadCenter
              }
          });
        }
  }
  audioSort(){
    this.setState({centerWindow:false})

     const { navigator } = this.props;
        if(navigator) {
          navigator.push({
              name: 'sortview',
              component : SortView,
              params: {
                  type: "audio",
                  cloud: this.state.data,
                  downloadCenter:this.downloadCenter


              }
          });
        }
  }
  videoSort(){
    this.setState({centerWindow:false})

    const { navigator } = this.props;
    if(navigator) {
      navigator.push({
        name: 'sortview',
        component : SortView,
        params: {
          type: "video",
          cloud: this.state.data,
          downloadCenter:this.downloadCenter
        }
      });
    }
  }
  labelSort(){
    this.setState({centerWindow:false})

    const { navigator } = this.props;
    if(navigator) {
      navigator.push({
        name: 'sortview',
        component : SortView,
        params: {
          type: "label",
          cloud: this.state.data,
          downloadCenter:this.downloadCenter
        }
      });
    }
  }

  clickDownload(){ //文件下载

   if(this.state.checkRows){
     for (var i = 0; i < this.state.checkRows.length; i++) {
       this.state.checkRows[i].progress = 0;
     }

     this.downloadCenter.download(this.state.checkRows);
   }
    const { navigator } = this.props;
    for (var i = 0; i < this.state.data.length; i++) {
      this.state.data[i].selected = false;
    }
    this.setState({edit:false,dataSource:this.state.dataSource.cloneWithRows(this.state.data)})
    if(navigator) {
      navigator.push({
        name: 'downloadControl',
        component: DownloadControl,
        params:{
          downdata: this.state.checkRows,
          uploadList: false,
          downloadCenter:this.downloadCenter
        }
      });
    }

      this.state.checkRows.length = 0;

  }
  clickDelete(){
    this.downloadCenter.delFile(this.state.checkRows);
    for (var i = 0; i < this.state.checkRows.length; i++) {
      this.state.data.remove(this.state.checkRows[i])
    }
    this.state.checkRows.length = 0;
    this.setState({edit:false,dataSource:this.state.dataSource.cloneWithRows(this.state.data)})
  }

  onActionSelected(position){
    if(position===0){
      if(this.state.topWindow === false){
        this.setState({
            topWindow: true,
        });
      }else{
        this.setState({
            topWindow: false,
        });
      }
    }

    if(position===1){
      if(this.state.edit == false){
          this.setState({edit: true,bottmWindow: true,topWindow:false});
      }else{
          this.setState({edit: false,bottmWindow: false});
      }
    }

    if(position===2){
      if(this.state.centerWindow==false){
        this.setState({centerWindow:true});
      }else{
        this.setState({centerWindow:false});
      }
    }
    if(position===3){
      const { navigator } = this.props;
      if(navigator) {
        navigator.push({
          name: 'downloadControl',
          component: DownloadControl,
          params:{
            uploadList:true,
            data:[],
            downloadCenter:this.downloadCenter
          }
        });
        this.setState({edit:false});
      }else {
        alert("路由为空");
      }
    }
    if(position===4){
      const { navigator } = this.props;
      var picDatas = FileTypeFilter.getFileByType(this.state.data,'pic');
      if(navigator) {
        navigator.push({
          name: 'timeLine',
          component: TimeLine,
          params:{
            data:this.state.data
          }
        });
        this.setState({edit:false});
      }else {
        alert("路由为空");
      }
    }

  }

  render() {
    var menu,load;
    load =  (<View style={styles.progressParent}>
      <ProgressBarAndroid  style={styles.rowProgress}/>
      <Text style={styles.loadtext}>加载中</Text></View>)
    if(this.state.topWindow===true){
      menu = <View style={styles.topWindow}>
        <View style={styles.topWindowRow}>
          <TouchableOpacity onPress={this.goRecent.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/recentUploadoff.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goFile.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/fileoff.png')} />
          </TouchableOpacity>

          <TouchableOpacity onPress={this.goSlide.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/slideoff.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goPic.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/picoff.png')} />
          </TouchableOpacity>
        </View>
        <View style={styles.topWindowRow}>
          <TouchableOpacity onPress={this.goMusic.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/musicoff.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goVideo.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/videooff.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goLabel.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/labeloff.png')} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.goRecent.bind(this)}>
            <Image
              style={styles.modalImgStyle}
              source={require('./img/recentUploadoff.png')} />
          </TouchableOpacity>
        </View>
        <Text style={styles.divideLine}/>
      </View>
    }
    return(
      <View style={{flex:1}}>
        <ToolbarAndroid

        title={'文件'}
        style={styles.toolBar}
        actions={[
          {title: '分类',  show: 'never'},
        {title: '编辑',  show: 'never'},
        {title: '上传',  show: 'never'},
        {title: '传输列表',  show: 'never'},
        {title:'时间线',show:'always'},
        ]}
        onIconClicked={this.onIconClicked.bind(this)}
        onActionSelected={this.onActionSelected.bind(this)}/>

        <Modal
          style={styles.modalStyle}
          visible = {this.state.centerWindow}>
          <View style={styles.modalView}>
            <View style={{alignItems:'center',justifyContent:'center'}}>
            <View><Text style={styles.modalViewTitle}>选择上传类型</Text></View>
            <View>
            <Image style={styles.modalDivide} source={require('./img/divide.png')}></Image>
            </View>
            <View style={{flexDirection:'row',marginTop:10}}>
              <TouchableOpacity onPress={this.fileSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/fileoff.png') } />
              </TouchableOpacity>
              <TouchableOpacity onPress={this.slideSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/slideoff.png') } />
                </TouchableOpacity>
              <TouchableOpacity onPress={this.picSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/picoff.png') } />
              </TouchableOpacity>
            </View>
            <View style={styles.modalImgRow}>
              <TouchableOpacity onPress={this.audioSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/musicoff.png') } />
              </TouchableOpacity>
              <TouchableOpacity onPress={this.videoSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/videooff.png') } />
              </TouchableOpacity>
              <TouchableOpacity onPress={this.labelSort.bind(this)}>
              <Image
                style={styles.modalImage}
                source={require('./img/labeloff.png') } />
              </TouchableOpacity>
            </View>
          </View>
        </View>
        </Modal>
        {
          menu
        }
        {
          (!this.state.edit  && !this.state.data) && load
        }
        { !this.state.edit  &&
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow.bind(this)}
            renderSectionHeader={this._renderSectionHeader.bind(this)}
            automaticallyAdjustContentInsets={true}
          ></ListView>
        }

        { this.state.edit &&
          <View style={{flex:1,marginTop:2}}>
            <ListView
              dataSource={this.state.dataSource}
              renderRow={this._renderRowForEdit.bind(this)}
              automaticallyAdjustContentInsets={true}
              ></ListView>
            <View><Text style={styles.bottomModalLine}/></View>
            <View style={styles.bottomModal}>

              <View style={styles.modalImg}>
                <TouchableOpacity onPress={this.clickDownload.bind(this)}>
                  <Image
                    style={styles.modalImgSize}
                    source={require('./img/download.png')} />
                </TouchableOpacity>
              </View>

              <View style={styles.modalImg}>
                <Image
                  style={styles.modalImgSize}
                  source={require('./img/share.png')} />
              </View>
              <View style={styles.modalImg}>
                <Image
                  style={styles.modalImgSize}
                  source={require('./img/port.png')} />
              </View>

              <View style={styles.modalImg}>
                <TouchableOpacity onPress={this.clickDelete.bind(this)}>
                <Image
                  style={styles.modalImgSize}
                  source={require('./img/delete.png')} />
                </TouchableOpacity>
              </View>
              <View style={styles.modalImg}>
                <Image
                  style={styles.modalImgSize}
                  source={require('./img/label.png')} />
              </View>
            </View>
          </View>
        }
      </View>
    );
  }

  onIconClicked(){
    this.props.drawer();
  }

  clickSearch(){
    alert('正在搜索。。');
  }

  _pressRow(file,rowID){
    if(file.type=="cm:folder"){
      this.fetchData(urls[urls.length-1]);
    }else{
      getStorage().getTicket().then( ret => {
        var ticket = ret.Ticket;
        var url = "http://42.159.143.17:6080/alfresco/webdav"+file.webdavpath+"?ticket="+ticket;
        RNFileSearch.openOnlineFile(encodeURI(url),file.name);
      }).catch( err => {
      });

    }
  }


  _pressRowForEdit(file,rowID){
      if(file.selected){
        file.selected = false;
        this.state.checkRows.remove(file);
        this.setState({
          dataSource:this.state.dataSource.cloneWithRows(this.state.data)
        });
      }else{

        file.selected = true;
        this.state.checkRows.push(file);
        console.log('选择项false',this.state.checkRows);
        this.setState({
          dataSource:this.state.dataSource.cloneWithRows(this.state.data)
        });
      }
  }

  getLocalTime(time){
   var now = new Date(parseInt(time))
   var year=now.getFullYear();
   var month=now.getMonth()+1;
   var date=now.getDate();
   var hour=now.getHours();
   var minute=now.getMinutes();
   var second=now.getSeconds();
   return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
  }

  _renderRow(file: object,rowID: number) {
    const imageIcon = FileIcon(file.webdavpath,this.props.ticket);
      return (
        <TouchableOpacity onPress={()=>this._pressRow(file,rowID)}>
          <View style={styles.container}>
            <Image
              source={imageIcon}
              style={styles.thumbnail}
              ></Image>
            <View>
              <Text style={styles.title} numberOfLines={1}>{file.name}</Text>
              <Text style={styles.year}>{this.getLocalTime(file.updated)}</Text>
            </View>
          </View>
        </TouchableOpacity>
      );
  }
  _renderRowForEdit(file,sectionID,rowID) {
    const imageIcon = FileIcon(file.webdavpath,this.props.ticket);
        var select;
        if(file.selected == true){
          select = <View>
                    <Image
                      style={styles.rowIcon}
                      source={require('./img/check.png')} />
                   </View>;
        }else{
           select = <View>
                    <Image
                      style={styles.rowIcon}
                      source={require('./img/unchecked.png')} />
                   </View>;
        }
        return (
            <TouchableOpacity onPress={()=>this._pressRowForEdit(file,rowID)}>
              <View style={styles.container}>
                <Image
                  source={imageIcon}
                  style={styles.thumbnail}
                  ></Image>
                <View style={styles.rightContainer} >
                  <Text style={styles.title} numberOfLines = {1}>{file.name}</Text>
                  <Text style={styles.year}>{this.getLocalTime(file.updated)}</Text>
                </View>
                {
                  select
                }
              </View>
            </TouchableOpacity>
          );
  }
  _renderSectionHeader(){
    return (
      <TouchableOpacity onPress={this.clickSearch.bind(this)}>
        <Image style={styles.subHead} source={require('./img/search_bg.png')}>
          <View style={[styles.subHeadContent]}>
            <Image style={styles.subHeadImg} source={require('./img/search.png')}/>
            <Text style={styles.subHeadText}>搜索</Text>
          </View>
        </Image>
      </TouchableOpacity>

    );
  }
  midMenu(){
    if(this.state.centerWindow==false){
      this.setState({centerWindow:true});
    }else{
      this.setState({centerWindow:false});
    }
  }

}

const styles = StyleSheet.create({
  container: {
    height: 65,
    flexDirection: 'row',
    backgroundColor:'#FFFFFF'
  },
  rightContainer: {
    flex:1,
    marginLeft:8,
  },
  thumbnail: {
    marginTop:10,
    marginLeft:15,
    width: 40,
    height: 50,
    // resizeMode: 'stretch'
  },
  title:{
    marginBottom: 8,
    marginTop:13,
    marginLeft:15,
    width:240,
    color:'black',
    fontSize:16
  },
  year:{
    fontSize: 12,
    marginTop:-5,
    marginLeft:15,
  },
  rowIcon:{
    width:10,
    height:10,
    marginTop:30,
    marginRight:20
  },
  drawerContainer: {
      width:300,
      height:150,
      backgroundColor: 'transparent'
    },
  bg: {
        position: 'absolute',
        left: 0,
        top: 0,
        width: 300,
        height: 150,
  },
  modal: {
    top: 50,
    width: Dimensions.get('window').width,
    height: 100,
    backgroundColor: 'red',    //rgba(58, 93, 15, 0.8)
    overflow: 'visible'
  },
  modalImg: {
    flex:1,
    alignItems:'center',
    justifyContent:'center'
  },
  modalImgSize: {
    width: 30,
    height: 30
  },
  modalImgStyle: {
    height:50,
    width:width/4,
    alignItems:'center',
    justifyContent:'center'
  },
  topWindow:{
    height:100,
    marginBottom:10,
  },
  topWindowRow: {
    flexDirection:'row',
    height:50,
    marginTop:5
  },
  divideLine: {
    backgroundColor:'#E9E9E9',
    height:1
  },
  toolBar: {
    height:56,
    backgroundColor: '#6d9eeb'
  },
  modalStyle:{
    backgroundColor:'rgba(0,0,0,0.8)',
    top:0,
    bottom:0,
    left:0,
    right:0
  },
  modalView: {
    marginTop:100,
    marginLeft:40,
    marginRight:40,
    backgroundColor:'#EFEFEF'
  },
  modalViewTitle: {
    textAlign:'center',
    marginTop:20,
    color:'#000000'
  },
  modalDivide: {
    height:1,
    width:230,
    marginTop:20
  },
  modalImgRow: {
    flexDirection:'row',
    marginBottom:10
  },
  modalImage: {
    width:77,
    height:70
  },
  bottomModal: {
    backgroundColor:'#FFFFFF',
    height:50,
    flexDirection:'row'
  },
  bottomModalLine: {
    height:1,
    backgroundColor:'#E9E9E9'
  },
  subHead: {
    height: 40,
    width: width,
    alignItems:'center',
    justifyContent:'center'
  },
  subHeadContent: {
    flexDirection:'row',
    alignItems:'center',
    width: 55,
    height:30,
  },
  subHeadImg: {
    width: 15,
    height: 15
  },
  subHeadText: {
    marginLeft:10,
    fontSize: 15
  },
  progressParent:{
    height:500,
    alignItems:'center',
    justifyContent:'center'
  },
  rowProgress:{
    height:100,
    width:100
  },
  loadtext:{
    alignItems:'center',
    marginTop:-60

  }
});


function mapStateToProps(store){
    return{
      ticket : store.Login.ticket
    };
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({},dispatch);
}

export default connect (mapStateToProps,mapDispatchToProps)(MainScreen);
